package com.extr.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.extr.controller.domain.ExamFinishParam;
import com.extr.controller.domain.QuestionImproveResult;
import com.extr.controller.domain.QuestionPointResult;
import com.extr.controller.domain.QuestionQueryResult;
import com.extr.domain.exam.ExamHistory;
import com.extr.domain.exam.ExamPaper;
import com.extr.domain.practice.LogException;
import com.extr.domain.practice.PracticeRecord;
import com.extr.domain.question.KnowledgePoint;
import com.extr.domain.question.Question;
import com.extr.domain.question.QuestionContent;
import com.extr.domain.user.User;
import com.extr.security.LoginUserInfo;
import com.extr.security.UserInfo;
import com.extr.service.ExamService;
import com.extr.service.LogExceptionService;
import com.extr.service.PracticeRecordService;
import com.extr.service.PracticeService;
import com.extr.service.QuestionService;
import com.extr.service.UserService;
import com.extr.util.Page;
import com.extr.util.StandardPasswordEncoderForSha1;
import com.extr.util.xml.Object2Xml;

@Controller 
public class ClientInterface {
    
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	private QuestionService questionService;
	
	@Autowired
	private ExamService examService;
	
	@Autowired
	private PracticeService practiceService;
	
	@Autowired
	private PracticeRecordService recordService;
	
	@Autowired
	private LogExceptionService logExceptionService;
	
	
	
	@RequestMapping(value = "/getHttpData.do")
	@ResponseBody
	public Map<String, Object> getHttpData(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String method = "getHttpData.do";
		try {
			method = (String) request.getParameter("method");
			if ("validataUser".equalsIgnoreCase(method)) {
				map = validataUser(request);
			} else if ("getExamList".equalsIgnoreCase(method)) {
				map = getExamList(request);
			} else if ("getExamPaper".equalsIgnoreCase(method)) {
				map = getExamPaper(request);
			} else if ("getRandomPractice".equalsIgnoreCase(method)) {
				map = getRandomPractice(request);
			} else if ("getClassifyList".equalsIgnoreCase(method)) {
				map = getClassifyList(request);
			} else if ("getPracticeImprove".equalsIgnoreCase(method)) {
				map = getPracticeImprove(request);
			} else if ("getSubmitExam".equalsIgnoreCase(method)) {
				map = getSubmitExam(request);
			} else if ("getExamPointGet".equalsIgnoreCase(method)) {
				map = getExamPointGet(request);
			} else if ("getPracticeRecord".equalsIgnoreCase(method)) {
				map = getPracticeRecord(request);
			} else if ("getChangePassword".equalsIgnoreCase(method)) {
				map = getChangePassword(request);
			}else{
				map.put("result", false);
				map.put("messageInfo", "method:方法名错误!");
				map.put("data", null);
			}
		} catch (Exception e) {
			LogException logEx = new LogException();
			logEx.setLogName(method);
			logEx.setLogException(e.getMessage());
			logEx.setCreateTime(new Date());
			logExceptionService.addLog(logEx);
			map.put("result", false);
			map.put("messageInfo", e.getMessage());
			map.put("data", null);
		}

		return map;
	}

	/**
	 * 用户登录
	 * 
	 * @param user
	 * @return
	 */
	private Map<String, Object> validataUser(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();

		String username = (String) request.getParameter("userName");
		String password = (String) request.getParameter("passWord");
		username = (username == null) ? "" : username.toString();
		password = (password == null) ? "" : password.toString();

		String sh1Password = password + "{" + username + "}";
		PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
		String result = passwordEncoder.encode(sh1Password);
		UserInfo userDetails = (UserInfo) userDetailsService
				.loadUserByUsername(username);
		if (!passwordEncoder.matches(userDetails.getPassword(), result)
				|| "0".equals(userDetails.getEnabled()) || userDetails == null) {
			map.put("result", false);
			map.put("messageInfo", "用户名或密码错误！");
			map.put("data", null);
		} else {
			LoginUserInfo user = new LoginUserInfo();
			user.setUserid(userDetails.getUserid());
			user.setTrueName(userDetails.getUsername());
			user.setFieldId(userDetails.getFieldId());
			user.setFieldName(userDetails.getFieldName());

			map.put("result", true);
			map.put("messageInfo", "登陆验证通过");
			map.put("data", user);
		}

		return map;
	}
	
	/**
	 * 考试列表
	 * 
	 * @param user
	 * @return
	 */
	public Map<String, Object> getExamList(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String fieldId = (String) request.getParameter("fieldId");
		int fieldID = Integer.parseInt(fieldId);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		List<ExamPaper> practicepaper = examService.getExamPaperListByField(
				fieldID, 2, time);
		int count = practicepaper.size();
		for (int i = 0; i < count; i++)// 不需要content 将content置空
		{
			String content = "";
			practicepaper.get(i).setContent(content);
		}
		map.put("result", true);
		map.put("messageInfo", "获取考试列表成功");
		map.put("data", practicepaper);

		return map;
	}
	
	/**
	 * 获取考试题目
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, Object> getExamPaper(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = (String) request.getParameter("userId");
		int userID = Integer.parseInt(userId);
		String paperId = (String) request.getParameter("paperId");
		int paperID = Integer.parseInt(paperId);
		ExamHistory examHistory = examService
				.getUserExamHistoryByUserIdAndExamPaperId(userID, paperID);
		ExamPaper examPaper = examService.getExamPaperById(paperID);
		int duration = examPaper.getDuration();

		String content = examPaper.getContent();
		if (examHistory != null) {
			if (examHistory.getExamAgain() == 0) {
				map.put("result", false);
				map.put("messageInfo", "你已经参加过考试，如果要重新考试请联系管理员！");
				map.put("data", null);
				return map;
			}
			examHistory.setContent(content);
			examHistory.setExamAgain(0);
			examService.updateExamHistory(examHistory);
		} else {
			examHistory = new ExamHistory();
			examHistory.setContent(content);
			examHistory.setExamPaperId(paperID);
			examHistory.setUserId(userID);
			examHistory.setDuration(examPaper.getDuration());
			examHistory.setCreateTime(new Date());
			examService.addUserExamHistory(examHistory);
		}
		@SuppressWarnings("unchecked")
		List<QuestionQueryResult> questionList = Object2Xml.toBean(content,
				List.class);
		ArrayList<QuestionContent> quelist = new ArrayList<QuestionContent>();
		for (int index = 0; index < questionList.size(); index++) {
			QuestionContent qc = Object2Xml.toBean(questionList.get(index)
					.getContent(), QuestionContent.class);
			questionList.get(index).setContent("");
			questionList.get(index).setTitle(qc.getTitle());
			questionList.get(index).setTitleImg(qc.getTitleImg());
			questionList.get(index).setChoiceList(qc.getChoiceList());
			questionList.get(index).setChoiceImgList(qc.getChoiceImgList());
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();

		resultMap.put("examHistoryId", examHistory.getHistId());
		resultMap.put("examPaperId", paperID);
		resultMap.put("duration", duration * 60);
		resultMap.put("questionList", questionList);

		map.put("result", true);
		map.put("messageInfo", "获取考试成功");
		map.put("data", resultMap);

		return map;
	}

	/**
	 * 获取随机练习题目
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, Object> getRandomPractice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> fieldIdList = new ArrayList<Integer>();
		String fieldId = (String) request.getParameter("fieldId");
		int fieldID = Integer.parseInt(fieldId);
		fieldIdList.add(fieldID);
		List<Integer> typeIdList = new ArrayList<Integer>();
		typeIdList.add(1);
		typeIdList.add(2);
		typeIdList.add(3);
		typeIdList.add(4);
		List<QuestionQueryResult> qqrList = questionService
				.getQuestionQueryResultListByFieldIdList(fieldIdList,
						typeIdList, 20);

		for (int index = 0; index < qqrList.size(); index++) {
			QuestionContent qc = Object2Xml.toBean(qqrList.get(index)
					.getContent(), QuestionContent.class);
			qqrList.get(index).setContent("");
			qqrList.get(index).setTitle(qc.getTitle());
			qqrList.get(index).setTitleImg(qc.getTitleImg());
			qqrList.get(index).setChoiceList(qc.getChoiceList());
			qqrList.get(index).setChoiceImgList(qc.getChoiceImgList());
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();

		resultMap.put("examHistoryId", 0);
		resultMap.put("examPaperId", 0);
		resultMap.put("duration", 0);
		resultMap.put("questionList", qqrList);

		map.put("result", true);
		map.put("messageInfo", "获取数据成功");
		map.put("data", resultMap);

		return map;
	}
	
	/**
	 * 获取强化练习知识点列表
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, Object> getClassifyList(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();

		String userId = (String) request.getParameter("userId");
		int userID = Integer.parseInt(userId);
		User user = userService.getUserById(userID);

		if (user == null) {
			map.put("result", false);
			map.put("messageInfo", "获取用户数据失败！");
			map.put("data", null);
			return map;
		}
		Object userInfo = (UserInfo) userDetailsService.loadUserByUsername(user
				.getUsername());
		List<KnowledgePoint> kl = null;
		List<Integer> idList = new ArrayList<Integer>();
		Map<String, List<QuestionImproveResult>> classifyMap = new HashMap<String, List<QuestionImproveResult>>();
		int fieldId = questionService.getMinFieldId();

		if (userInfo instanceof String) {
			kl = questionService.getKnowledgePointByFieldId(fieldId, null);
		} else {
			List<KnowledgePoint> kpz = questionService
					.getKnowledgePointByFieldId(fieldId, null);
			kl = questionService.getKnowledgePointByFieldId(
					((UserInfo) userInfo).getFieldId(), null);

			kpz.addAll(kl);
			kl = kpz;
		}
		for (KnowledgePoint klp : kl) {
			idList.add(klp.getPointId());
		}

		List<QuestionImproveResult> questionImproveList = questionService
				.getQuestionImproveResultByQuestionPointIdList(idList);

		for (QuestionImproveResult qir : questionImproveList) {
			List<QuestionImproveResult> tmpList = new ArrayList<QuestionImproveResult>();

			if (classifyMap.containsKey(qir.getQuestionPointName()))
				tmpList = classifyMap.get(qir.getQuestionPointName());
			else
				tmpList = new ArrayList<QuestionImproveResult>();

			tmpList.add(qir);
			classifyMap.put(qir.getQuestionPointName(), tmpList);
		}

		List<QuestionPointResult> pointList = new ArrayList<QuestionPointResult>();
		for (Map.Entry<String, List<QuestionImproveResult>> entry : classifyMap
				.entrySet()) {
			QuestionPointResult point = new QuestionPointResult();
			point.setPointName(entry.getKey());
			point.setList(entry.getValue());
			pointList.add(point);
		}

		map.put("result", true);
		map.put("messageInfo", "获取数据成功");
		map.put("data", pointList);

		return map;
	}
	
	/**
	 * 获取强化练习的详细
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, Object> getPracticeImprove(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String knowledgePointId = request.getParameter("knowledgePointId");
		String questionTypeId = request.getParameter("questionTypeId");
		List<QuestionQueryResult> qqrList = questionService
				.getQuestionAnalysisListByPointIdAndTypeId(
						Integer.parseInt(questionTypeId),
						Integer.parseInt(knowledgePointId));
		/*
		 * String questionTypeName = ""; String fieldName = ""; try{ fieldName =
		 * qqrList.get(0).getPointName().split(">")[1]; }catch(Exception e){
		 * e.getMessage(); }
		 * 
		 * List<QuestionType> questionTypeList =
		 * questionService.getQuestionTypeList(); for(QuestionType qt :
		 * questionTypeList){
		 * 
		 * if(qt.getId() == Integer.parseInt(questionTypeId)){ questionTypeName
		 * = qt.getName(); break; } } int amount = qqrList.size();
		 */
		for (int index = 0; index < qqrList.size(); index++) {
			QuestionContent qc = Object2Xml.toBean(qqrList.get(index)
					.getContent(), QuestionContent.class);
			qqrList.get(index).setContent("");
			qqrList.get(index).setTitle(qc.getTitle());
			qqrList.get(index).setTitleImg(qc.getTitleImg());
			qqrList.get(index).setChoiceList(qc.getChoiceList());
			qqrList.get(index).setChoiceImgList(qc.getChoiceImgList());
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();

		resultMap.put("examHistoryId", 0);
		resultMap.put("examPaperId", 0);
		resultMap.put("duration", 0);
		resultMap.put("questionList", qqrList);

		// resultMap.put("questionList", qqrList);
		// resultMap.put("amount", amount);
		// resultMap.put("fieldName", fieldName);
		// resultMap.put("questionTypeName", questionTypeName);
		// resultMap.put("practiceName", "强化练习");

		if (resultMap.size() > 0) {
			map.put("result", true);
			map.put("messageInfo", "获取数据成功");
			map.put("data", resultMap);
		} else {
			map.put("result", false);
			map.put("messageInfo", "获取数据失败！");
			map.put("data", null);
		}
		return map;
	}
	
	/**
	 * 考试提交
	 * 
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getSubmitExam(HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String jsonStr = request.getParameter("efp");
		ObjectMapper objectMapper = new ObjectMapper();
		ExamFinishParam efp = objectMapper.readValue(jsonStr, ExamFinishParam.class);
		ExamHistory examHistory = examService.getUserExamHistoryByHistId(efp
				.getExam_history_id());
		List<QuestionQueryResult> questionList = Object2Xml.toBean(
				examHistory.getContent(), List.class);
		float pointGet = 0f;
		for (QuestionQueryResult qqr : questionList) {
			if (efp.getAs().get(qqr.getQuestionId()) == null) {
				continue;
			}
			if (qqr.getAnswer().equals(
					efp.getAs().get(qqr.getQuestionId()).getAnswer()))
				pointGet += qqr.getQuestionPoint();
		}
		// 计算得分
		examHistory.setPointGet(pointGet);
		examHistory.setAnswerSheet(Object2Xml.toXml(efp.getAs()));
		examHistory.setSubmitTime(new Date());
		examHistory.setDuration(efp.getDuration());
		examService.updateExamHistory(examHistory);

		map.put("result", true);
		map.put("messageInfo", "获取数据成功");
		map.put("data", pointGet);

		return map;
	}
	
	/**
	 * 获取考试分数
	 * 
	 * @param request
	 * @return
	 */
	private Map<String, Object> getExamPointGet(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = (String) request.getParameter("userId");
		int userID = Integer.parseInt(userId);

		List<ExamHistory> hisList = examService.getUserExamHistoryListByUserId(
				userID, null);

		for (int i = 0; i < hisList.size(); i++) {
			hisList.get(i).setContent("");
			hisList.get(i).setAnswerSheet("");
		}
		map.put("result", true);
		map.put("messageInfo", "获取数据成功！");
		map.put("data", hisList);

		return map;
	}
	
	/**
	 * 获取练习统计
	 * 
	 * @param request
	 * @return
	 */
	private Map<String, Object> getPracticeRecord(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String answer = request.getParameter("answer");
		String userId = request.getParameter("userId");
		String questionId = request.getParameter("questionId");

		Question question = questionService.getQuestionByQuestionId(Integer
				.parseInt(questionId));
		int right = 0;
		if (question.getAnswer().equals(answer)) {
			right = 1;
		}
		PracticeRecord record = new PracticeRecord();
		record.setQuestionId(question.getId());
		record.setUserId(Integer.parseInt(userId));
		record.setRecordTime(new Date());
		record.setUserRight(right);
		record.setUserAnswer(answer);

		recordService.addRecord(record);

		map.put("result", true);
		map.put("messageInfo", "获取数据成功！");
		map.put("data", "");

		return map;
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @return
	 */
	private Map<String, Object> getChangePassword(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = (String) request.getParameter("userId");
		String newPassword = (String) request.getParameter("password");

		int userID = Integer.parseInt(userId);
		User user = userService.getUserById(userID);

		String password = newPassword + "{" + user.getUsername() + "}";
		PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
		String resultPassword = passwordEncoder.encode(password);
		user.setPassword(resultPassword);
		userService.updateUser(user, null);

		map.put("result", true);
		map.put("messageInfo", "修改密码成功！");
		map.put("data", "");

		return map;
	}
}
